//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Text.RegularExpressions;

namespace CommunityServer.Components
{
	/// <summary>
	/// Summary description for TextTokens.
	/// </summary>
	public class TextTokens
	{
		private TextTokens(){}

		private static string CacheKey(int sectionID)
		{
			return string.Format("TokenKey:{0}:{1}", sectionID.ToString(), CSContext.Current.SettingsID);
		}

		public static ArrayList GetTokens(int sectionID)
		{
			string key = CacheKey(sectionID);
			ArrayList list = CSCache.Get(key) as ArrayList;
			if(list == null)
			{
				list = CommonDataProvider.Instance().GetTokens(sectionID);
				CSCache.MicroInsert(key,list,5);
			}
			return list;
		}

		public static int Add(TextToken token)
		{
			CSCache.Remove(CacheKey(token.SectionID));
			return CommonDataProvider.Instance().AddToken(token);
			
		}

		public static void Update(TextToken token)
		{
			CommonDataProvider.Instance().UpdateToken(token);
			CSCache.Remove(CacheKey(token.SectionID));
		}

		public static void Delete(TextToken token)
		{
			CommonDataProvider.Instance().DeleteToken(token);
			CSCache.Remove(CacheKey(token.SectionID));
		}



		public static string Format(ITextToken token, string text)
		{
			if(Regex.IsMatch(text,token.Pattern, RegexOptions.IgnoreCase|RegexOptions.Compiled))
			{
				text = token.FormatText(text);
			}
			
			return text;	
		}

	}

}
